package com.commonlib.downloadmgr.base;

import java.util.ArrayList;
import java.util.HashSet;

import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;


public abstract class DownloadBaseAdapter<T> extends BaseAdapter{
	private static final String TAG = DownloadBaseAdapter.class.getSimpleName();
	private HashSet<String> itemsSlelcted = new HashSet<String>();
	private boolean isControlStatus = false;
	
	public HashSet<String> getItemsSlelcted() {
		return itemsSlelcted;
	}

	public void setItemsSlelcted(HashSet<String> itemsSelected) {
		this.itemsSlelcted = itemsSelected;
	}

	public boolean isControlStatus() {
		return isControlStatus;
	}

	public void setControlStatus(boolean isControlStatus) {
		this.isControlStatus = isControlStatus;
	}

	public void addSelectedItem(String id){
		itemsSlelcted.add(id);
		notifyDataSetChanged();
	}
	
	public void addSelectedItems(ArrayList<String> items){
		itemsSlelcted.addAll(items);
		notifyDataSetChanged();
	}
	
	public void removeSelectedItem(String id){
		itemsSlelcted.remove(id);
		notifyDataSetChanged();
	}
	
	public void removeSelectedItems(ArrayList<String> items){
		itemsSlelcted.removeAll(items);
		notifyDataSetChanged();
	}
	
	public void clearSelectedItems(){
		itemsSlelcted.clear();
		notifyDataSetChanged();
	}
	
	public boolean isItemSelected(String id){
		return itemsSlelcted.contains(id);
	}
	
	public void deleteDownloadJobsSelected(){
		getDownloadManager().removeDownloadJobs(itemsSlelcted, false, true);
		notifyDataSetChanged();
		isControlStatus = getDownloadManager().getAllJobs().isEmpty() ? false : true;
		Log.v(TAG, "deleteDownloadJobsSelected, ids:" + itemsSlelcted.toString());
	}
	
	public void selectAllItems(){
		ArrayList<DownloadBaseJob<T>> listDownloadJobs = getDownloadManager().getAllJobs();
		ArrayList<String> ids = new ArrayList<String>();
		for (DownloadBaseJob<T> job : listDownloadJobs) {
			ids.add(job.getId());
		}
		if (!ids.isEmpty()) {
			itemsSlelcted.addAll(ids);
		}
		notifyDataSetChanged();
		Log.v(TAG, "selectAllItems, ids:" + itemsSlelcted.toString());
	}

	@Override
	public int getCount() {
		return getDownloadManager().getAllJobs().size();
	}

	@Override
	public DownloadBaseJob<T> getItem(int position) {
		ArrayList<DownloadBaseJob<T>> allJobs = getDownloadManager().getAllJobs();
		return allJobs.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	/**
	 * Override by subclass
	 */
	public abstract View getView(int position, View convertView, ViewGroup parent);
	
	/**
	 * Override by subclass
	 */
	public abstract DownloadBaseManager<T> getDownloadManager();

}
